﻿using OIDCDemo.Questions;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Security.Claims;
using Volo.Abp.Uow;
using Volo.Abp.Users;

namespace OIDCDemo.Extensions
{
    public class CustomCurrentUser : CurrentUser
    {
        private readonly ICurrentPrincipalAccessor _currentPrincipalAccessor;
        private readonly IRepository<Question> _questionRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;

        public CustomCurrentUser(
            ICurrentPrincipalAccessor principalAccessor,
            IRepository<Question> questionRepository,
            IUnitOfWorkManager unitOfWorkManager) : base(principalAccessor)
        {
            _currentPrincipalAccessor = principalAccessor;
            _questionRepository = questionRepository;
            _unitOfWorkManager = unitOfWorkManager;
        }

        public override Guid? Id => GetCurrentId().ConfigureAwait(false).GetAwaiter().GetResult();

        public async Task<Guid?> GetCurrentId()
        {
            var userIdClaim = FindClaim(AbpClaimTypes.UserId);
            if (userIdClaim == null)
            {
                return null;
            }

            using var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: false);
            var question = await _questionRepository.FirstOrDefaultAsync();
            await uow.CompleteAsync();

            return question.Id;
        }

        public override Claim FindClaim(string claimType)
        {
            return _currentPrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == claimType);
        }
    }
}
